<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
<#include "head.ftl" />
<link href="${st.resDomain}/common/js/bootstrap-3.3.5/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="body-box container-fluid">
	<div class="rhead">
		<div class="rpos">当前位置: 分类管理 - 列表</div>
		<div class="clear"></div>
		
	</div>
	<div class="rhead">
		<div style="clear:both;margin-left:50px;">
			<div id="categoryList" class="ztree"></div>
		</div>
	</div>
	<!-- Modals -->
	<div class="modal" id="modal_delete" role="dialog" aria-labelledby="loginLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="loginLabel">删除分类</h4>
	      </div>
	      <div class="modal-body">
   			<div class="form-group">
             <p>确定要删除“<span id="delName"></span>”吗？</p>
             <input type="hidden" id="delId" value=""/>
     		 <p>
       		 <label>原商品移动到：<em style="color:red;">*</em></label>
       		 <span id="catSelectContent"></span>
     		 </p>
    		</div>
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal" data-key="Esc">取消</button>
	        <button id="delDoBt" type="button" class="btn btn-success" data-key="Enter">确定</button>
	      </div>
	    </div>
	  </div>
	</div>
	<div class="modal" id="modal_tip" role="dialog" aria-labelledby="tipLabel" data-backdrop="false" data-keyboard="false">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-body" style="overflow: hidden;">
	      	<div class="col-xs-2 col-sm-2 loading"></div>
	      	<div class="col-xs-10 col-sm-10"><p class="form-control-static" style="font-size: 16px;line-height: 24px;">请稍候...</p></div>
	      </div>
	    </div>
	  </div>
	</div>
	
</div>

</body>
<script src="${st.resDomain}/common/js/bootstrap-3.3.5/bootstrap.min.js" rel="stylesheet"></script>
<script>
	// 加载分类列表请求地址
	var listCategoryPath = g_domain + "/category/listWithSons/json";
	// 新增分类请求地址
	var addDoPath = g_domain + "/category/addDo/json";
	// 修改分类请求地址
	var editDoPath = g_domain + "/category/editDo/json";
	// 删除分类请求地址
	var delDoPath = g_domain + "/category/delDo/json";
	
	var setting = {
		view : {
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false
		},
		async : {
			enable : true,
			autoParam : ["catId"],
			dataFilter : dataFilter,
			url : "listSons/json"
		},
		edit : {
			enable : true,
			drag: {
				isCopy: false,
				isMove: true
			},
			renameTitle : "编辑",
			removeTitle : "删除",
			editNameSelectAll : true
		},
		data : {
			keep : {
				leaf : false,
				parent : true
			},
			key : {
				name : "name"
			},
			simpleData : {
				enable : true,
				idKey : "catId",
				pIdKey : "parentId",
				rootPId : null
			}
		},
		callback : {
			beforeRename : beforeRename,
			beforeRemove : beforeRemove,
			beforeDrop : beforeDrop
		}

	};
	
	var zTree = null;
	$(document).ready(function() {
		initZTree(null, null);
	});
	
	function initZTree(parentNode, callback) {
		var vars = {
			deep: 0
		};
		if(parentNode){
			vars = {
				"category.catId": parentNode.catId
			};
		}
		$.getJSON(listCategoryPath, vars, function(data) {
			var list = data.result;
			if (!list || list.length == 0) {
				return;
			}
			var nodes = [];
			for (var i = 0; i < list.length; i++) {
				var node = list[i];
				node.isParent = true;
				nodes.push(node);
			}
			$.fn.zTree.init($("#categoryList"), setting, nodes);
			if(callback){
				callback();
			}  
		});
	}
	
	function dataFilter(treeId, parentNode, responseData) {
		if (!responseData) return null;
		var parent = responseData.result;
		var list = parent.categories;
		var childNodes = [];
		if(!list){
			return;
		}
		for (var i = 0; i < list.length; i++) {
			var node = list[i];
			node.isParent = true;
			node.open = true;
			childNodes.push(node);
		}
		return childNodes;
	} 
	
	//显示“新增”按钮，并绑定操作事件
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增'  onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_" + treeNode.tId);
		if (btn) {
			btn.bind("click", function () {
				$.ajax({
					url : addDoPath,
					type : "post",
					dataType : "json",
					data : {"category.catId" : treeNode.catId, name: "新建分类"},
					success : function (data) {
						if(data.status !== 0){
							alert(data.message);
							return;
						}
						var node = data.result;
						node.isParent = true;
						zTree = $.fn.zTree.getZTreeObj("categoryList");
						if (treeNode.zAsync) {
							zTree.addNodes(treeNode, node);
						} else {
							zTree.reAsyncChildNodes(treeNode, "refresh");
						}
						
					}
				});
			});
		}
	}
	
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	}
	
	//编辑分类名称提交前回调函数，把更新内容提交至服务器
	function beforeRename(treeId, treeNode, newName){
		if(newName == treeNode.name) {
			return true;
		}
		//根据ajax请求结果， 确定回调函数的返回值
		var eFlag = false;
		$.ajax({
			url : editDoPath,
			async : false,
			type : "post",
			dataType : "json",
			data : {"catId" : treeNode.catId , "name" : newName},
			success : function (data) {
				if(data.status === 0){
					eFlag = true;
				}
			}
		});
		if (!eFlag) {
			showMsg("更新失败,请重试或者联系管理员!");
		}
		return eFlag;
	}
	
	//删除分类节点回调函数
	function beforeRemove(treeId, treeNode) {
		zTree = $.fn.zTree.getZTreeObj("categoryList");
		zTree.selectNode(treeNode);
		$("#delName").html(treeNode.name);
		$("#catSelectContent").html("");
		$("#delId").val(treeNode.catId);
		makeCategoryComboBox();
		$("#modal_delete").modal("show");
		return false; // 此时暂不删除节点，待按下弹出框“确定”按钮异步请求成功后再删除相应的节点
	}
	
	function makeCategoryComboBox(value) {
		$("#catSelectContent").categoryComboBox({
			type: -1,
			value: value,
			onSelect: function(deep, category) {
				
			}
		});
	}
	
	$("#delDoBt").click(function() {
		var delId = $("#delId").val();
		var bakupId = $("#catSelectContent").find("option:selected[value!='']:last").val();
		if (!bakupId) {
			showMsg("请将该分类下的商品移动到其他分类再删除");
			return;
		}
		$.post(delDoPath, {delId: delId, bakupId: bakupId}, function(data) {
			if (data.status !== 0) {
				showMsg("删除失败，请联系管理员");
				return;
			}
			$("#modal_delete").modal("hide");
			var zTree = $.fn.zTree.getZTreeObj("categoryList"),
			nodes = zTree.getSelectedNodes(),
			treeNode = nodes[0];
			zTree.removeNode(treeNode);
		});
	});
	
	// 节点拖拽操作结束之前的事件回调函数
	function beforeDrop (treeId, treeNodes, targetNode) {
		treeNode = treeNodes[0];
		var isDrop = window.confirm('确定要将 "' + treeNode.name + '" 及其所有子类移动到 "' + targetNode.name + '" 分类下吗？');
		if (!isDrop) {
			return false;
		}
		var param = {
			catId: treeNode.catId,
			"category.catId": targetNode.catId,
			deep: targetNode.deep + 1,
			type: targetNode.type
		};
		$.post(editDoPath, param, function(data){
			if (data.status === 0) {
				isDrop = true;
			} else {
				isDrop = false;
				showMsg("移动分类失败，请联系管理员");
			}
		});
		return isDrop;
	}
	
	// 消息提示
	function showMsg(msg) {
		var $el = $("#modal_tip");
		$el.find(".form-control-static").html(msg);
		$el.finish().modal('show');
		setTimeout(function() {
        	$el.modal('hide');
        },1500);
	}
</script>
</html>